﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using BugTracker.BTGridView;
using BugTracker.BusinessEntities.Entities.Issue;
using BugTracker.BusinessLogic.BTUser;
using BugTracker.BusinessLogic.Issue;
using BugTracker.BusinessLogic.Project;
using BugTracker.Core.Infrastructure.Exceptions;
using BugTracker.WebUX.WebCode;
using Microsoft.Practices.Unity;
using BugTracker.BusinessLogic.Issue.Details;

namespace BugTracker.WebUX.Workspace.Modules
{
    public partial class UCIssueList : System.Web.UI.UserControl
    {
        #region variables

        private IList<IssueType> type = new List<IssueType>();
        private IList<IssuePriorityType> priority = new List<IssuePriorityType>();
        private IList<IssueStatusType> status = new List<IssueStatusType>();
        private IList<User> users = new List<User>();
        private IList<IssueSeverityType> severity = new List<IssueSeverityType>();
        private IList<IssueResolutionType> resolution = new List<IssueResolutionType>();

        #endregion

        #region load

        protected void Page_Load(object sender, EventArgs e)
        {
            ModelBTGridView.BTGridViewPageIndexChanging += OnPageIndexChanged;
            if (!Page.IsPostBack)
            {
                BindData(0, ModelBTGridView.PageSize);
            }
        }

        #endregion 

        #region infobox

        private void SetInfoBoxError(string message)
        {
            ActionInfoBox.Visible = true;
            ActionInfoBox.Text = message;
            ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.red;
        }

        #endregion

        #region methods

        private void OnPageIndexChanged(object sender, BTPagerEventArgs e)
        {
            BindData(e.PageIndex, ModelBTGridView.PageSize);
        }

        private void BindData(int pageIndex, int pageCount)
        {
            int count = 0;
            if (ModelBTGridView.PTSorter == null)
            {
                ModelBTGridView.PTSorter = new Sorter("Name", SortDirection.Ascending);
            }
            if (BTSession.ProjectID.HasValue & BTSession.ProjectID != 0)
            {
                string sort = ModelBTGridView.PTSorter.Column + " " + ModelBTGridView.PTSorter.GetDirection();
                string where = string.Format("it.ProjectID={0}", BTSession.ProjectID.Value.ToString());
                var data = Global.IoC.Container.Resolve<IIssueDetailService>()
                    .PageSortWhere(
                                pageIndex,
                                pageCount,
                                where,
                                sort,
                                out count
                                );
                ModelBTGridView.VirtualCount = count;
                ModelBTGridView.DataSource = data;
                ModelBTGridView.DataBind();
            }
        }

        protected void ModelBTGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton deleteImgBtn = e.Row.FindControl("DeleteImageButton") as ImageButton;
                if (deleteImgBtn != null)
                {
                    deleteImgBtn.OnClientClick = Resources.Phrases.JavaScriptDeleteConfirm;
                }

                Image typeImg = e.Row.FindControl("TypeImage") as Image;
                if (typeImg != null)
                {
                    typeImg.ImageUrl = BTHttpApplication.AppPaths.FetchImageHandler +
                                    string.Format(
                                    BTHttpApplication.UrlParam.FETCH_FORMAT,
                                    3,
                                    ((Issue)e.Row.DataItem).IssueTypeID.ToString());
                }

                Image priorityImg = e.Row.FindControl("PriorityImage") as Image;
                if (priorityImg != null)
                {
                    priorityImg.ImageUrl = BTHttpApplication.AppPaths.FetchImageHandler +
                                    string.Format(
                                    BTHttpApplication.UrlParam.FETCH_FORMAT,
                                    6,
                                    ((Issue)e.Row.DataItem).IssuePriorityTypeID.ToString());
                }

               
                Image statusImg = e.Row.FindControl("StatusImage") as Image;
                if (statusImg != null)
                {
                    statusImg.ImageUrl = BTHttpApplication.AppPaths.FetchImageHandler +
                                    string.Format(
                                    BTHttpApplication.UrlParam.FETCH_FORMAT,
                                    4,
                                    ((Issue)e.Row.DataItem).IssueStatusTypeID.ToString());
                }

                Image severityImg = e.Row.FindControl("SeverityImage") as Image;
                if (severityImg != null)
                {
                    severityImg.ImageUrl = BTHttpApplication.AppPaths.FetchImageHandler +
                                    string.Format(
                                    BTHttpApplication.UrlParam.FETCH_FORMAT,
                                    8,
                                    ((Issue)e.Row.DataItem).IssueSeverityTypeID.ToString());
                }

                Image resolutionImg = e.Row.FindControl("ResolutionImage") as Image;
                if (resolutionImg != null)
                {
                    resolutionImg.ImageUrl = BTHttpApplication.AppPaths.FetchImageHandler +
                                    string.Format(
                                    BTHttpApplication.UrlParam.FETCH_FORMAT,
                                    5,
                                    ((Issue)e.Row.DataItem).IssueResolutionTypeID.ToString());
                }
            }
        }

        protected void ModelBTGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Select"))
            {
                GridViewRow row = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
                string redirectUrl = BTHttpApplication.AppPaths.IssueDetail +
                    "?" +
                    BTHttpApplication.UrlParam.ISSUE_ID +
                    "=" +
                    this.ModelBTGridView.DataKeys[row.RowIndex].Value.ToString();
                Response.Redirect(redirectUrl);
            }
            else if (e.CommandName.Equals("Delete"))
            {
                GridViewRow row = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
                try
                {
                    int id = Convert.ToInt32(this.ModelBTGridView.DataKeys[row.RowIndex].Value);
                    Global.IoC.Container.Resolve<IIssueService>().DeleteObject(id);
                    ActionInfoBox.Text = Resources.Phrases.DeleteSuccessful;
                    ActionInfoBox.MessageType = InfoBox.InfoBox.MsgType.green;
                    BindData(0, this.ModelBTGridView.PageSize);
                }
                catch (BugTrackerExpection exc)
                {
                    SetInfoBoxError(exc.Message);
                }
            }
        }

        protected void ModelBTGridView_RowDeleting(object sender, GridViewDeleteEventArgs e) { }

        protected void AddImageButton_Click(object sender, EventArgs e)
        {
            string redirectUrl = BTHttpApplication.AppPaths.IssueDetail;
            Response.Redirect(redirectUrl);
        }

        protected void RefreshBTButton_Click(object sender, EventArgs e)
        {
            BindData(0, ModelBTGridView.PageSize);
        }

        protected void ExportToExcelBTButton_Click(object sender, EventArgs e)
        {
            try
            {
                BugTracker.BTGridView.Export.ExportGridView("data.xls", this.ModelBTGridView);
            }
            catch (BTBusinessLogicException exc)
            {
                SetInfoBoxError(exc.Message);
            }
        }

        #endregion
    }
}